package com.xywy.find;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ErrorCode;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.util.ToastUtil;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.find.adapter.JkzhItemAdapter;
import com.xywy.find.bean.JkzhArticle;
import com.xywy.me.bean.UserKeeper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 健康知乎 - 专栏 plaze = 0 plaze：专栏id（母婴=1 减肥=2 保健=3 饮食=4）
 * 
 * @author xiaogd
 * 
 */
public class JkzhPlazeActivity extends BaseActivity {

	private static final String TAG = "JkgcPlazeActivity";
	private Context mContext;
	private int target = 0;
	private String titleStr = "";
	private ListView lv;
	private JkzhItemAdapter adapter;
	private int cid;
	private String userid;
	private SharedPreferences sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.find_jkzh_plaze);
		this.preInit();
		this.initView();
		this.loadData();
		this.setlistener();
	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.find_jkgc_plaze_title_bar);
		TextView tvTitle = titleBar.getTitle();
		TextView tvBack = titleBar.getTvBack();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		titleBar.onClickBack(this);
		tvTitle.setText(titleStr);
		tvBack.setText(getString(R.string.find_2));

		lv = (ListView) findViewById(R.id.lv_jkzh_item);
		lv.setDivider(null);
		adapter = new JkzhItemAdapter(mContext, titleStr);
	}

	@Override
	public void preInit() {
		mContext = this.context;
		Intent intent = getIntent();
		target = intent.getIntExtra("target", 0);
		titleStr = intent.getStringExtra("title");
		cid = intent.getIntExtra("id", -1);
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(this).getUserid();
	}

	@Override
	public void loadData() {
		this.sendMsg();
	}

	private List<JkzhArticle> articles;
	MyProgress myProgress;
	JSONObject json;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			if (msg.arg1 == ResultCode.SUCCESS) {
				if (msg.obj == null) {
					articles = (List<JkzhArticle>) FileUtil
							.getObject(FileUtil.JKZH + userid + cid);
					if (articles != null) {
						adapter.setData(articles);
						lv.setAdapter(adapter);
					}
					return;
				}
				try {
					json = new JSONObject(msg.obj.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				articles = getJkzhType(msg.obj.toString());
				FileUtil.saveObject(FileUtil.JKZH + userid + cid, articles);
				Log.e("jkzhpl", "articles  " + articles.size());
				// 填充数据
				adapter.setData(articles);
				lv.setAdapter(adapter);
			}else if (msg.arg1 == ErrorCode.ERR_NO_NETWORK) {
				Toast.makeText(JkzhPlazeActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
				setInfoNoNet();
			} 
		}

	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求
	public void sendMsg() {
		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.find_jkzh_articlelist);
		// 请求方式
		paramsParser.request = "get";

		// 请求参数
		// params.put("plaze",target);
		params.put("cid", cid);
		params.put("tag", 123);
		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}

		public <T extends Parser> void onFailure(T parserResult, int resultCode) {
			Message message = Message.obtain();
			message.arg1 = resultCode;
			handler.sendMessage(message);
		};
		public <T extends Parser> void onNoNetWork(T paramParser, int resultCode) {
			Message message = Message.obtain();
			message.arg1 = resultCode;
			handler.sendMessage(message);
		};
	};

	/**
	 * 封装返回的json
	 */
	private List<JkzhArticle> getJkzhType(String jsonStr) {
		List<JkzhArticle> list = Collections
				.synchronizedList(new ArrayList<JkzhArticle>());

		JkzhArticle article = new JkzhArticle();
		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			// JSONObject json1= jsonObject.optJSONObject(target+"");

			// String name = json1.optString("name");
			// MLog.i(TAG,"name====="+name);
			JSONArray jsonArray = jsonObject.optJSONArray("data");
			// JSONArray jsonArray = data.optJSONArray("data");
			if (null != jsonArray && jsonArray.length() > 0) {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);
					JkzhArticle clArticle = article.clone();
					clArticle.setArtId(json.optString("art_id"));
					clArticle.setTitle(json.optString("title"));
					clArticle.setNameD(json.optString("name_d"));
					clArticle.setType(json.optString("type"));
					clArticle.setContent(json.optString("reply"));
					clArticle.setDocImg(json.getString("image"));
					list.add(clArticle);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	private void setlistener() {
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {

				LinearLayout ll = (LinearLayout) view
						.findViewById(R.id.ll_jkzh_item);
				// ll.setBackgroundColor(mContext.getResources().getColor(R.color.find_jkgc_item_bg));

				JkzhArticle article = (JkzhArticle) lv.getItemAtPosition(i);
				MLog.i(TAG, "ARTI=========" + article.toString());

				Intent intent = new Intent(mContext, JkzhArticleActivity.class);
				intent.putExtra("artid", article.getArtId());
				// intent.putExtra("title",titleStr);
				intent.putExtra("target", target);
				mContext.startActivity(intent);
			}
		});

	}
	/**
	 * 没有网络 读本地缓存
	 */
	private void setInfoNoNet(){
		articles = (List<JkzhArticle>) FileUtil
				.getObject(FileUtil.JKZH + userid + cid);
		if (articles != null) {
			adapter.setData(articles);
			lv.setAdapter(adapter);
		}
	}
}
